package org.xtframe.web.action;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
import org.xtframe.bean.SystemConfig;
import org.xtframe.util.CommonUtil;
import org.xtframe.util.ContextUtil;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

@Repository("/uploadAction")
@Scope("prototype")
public class UploadAction extends BaseAction{
	
	private File upload;// 上传文件
	private String uploadFileName;// 上传文件名
	private String CKEditor;// 富文本编辑器名称
	private String CKEditorFuncNum;// 富文本编辑器回调方法

	// 图片文件上传
	public String image() {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try{
			if (ContextUtil.getCurrentUserData() == null) {
				return ajaxJsonErrorMessage("请先登录!");
			}
			if (upload == null) {
				return ajaxJsonErrorMessage("请选择上传文件!");
			}
			String allowedUploadImageExtension = getSystemConfig().getAllowedUploadImageExtension().toLowerCase();
			if (StringUtils.isEmpty(allowedUploadImageExtension)){
				return ajaxJsonErrorMessage("不允许上传图片文件!");
			}
			String imageExtension =  StringUtils.substringAfterLast(uploadFileName, ".").toLowerCase();
			String[] imageExtensionArray = allowedUploadImageExtension.split(SystemConfig.EXTENSION_SEPARATOR);
			if (!ArrayUtils.contains(imageExtensionArray, imageExtension)) {
				return ajaxJsonErrorMessage("只允许上传图片文件类型: " + allowedUploadImageExtension + "!");
			}
			int uploadLimit = getSystemConfig().getUploadLimit() * 1024;
			if (uploadLimit != 0) {
				if (upload != null && upload.length() > uploadLimit) {
					return ajaxJsonErrorMessage("文件大小超出限制!");
				}
			}
			File uploadImageDir = new File(ServletActionContext.getServletContext().getRealPath(SystemConfig.UPLOAD_IMAGE_DIR));
			if (!uploadImageDir.exists()) {
				uploadImageDir.mkdirs();
			}
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMM");
			String dateString = simpleDateFormat.format(new Date());
			String uploadImagePath = SystemConfig.UPLOAD_IMAGE_DIR + dateString + "/" + CommonUtil.getUUID() + "." + imageExtension;
			File file = new File(ServletActionContext.getServletContext().getRealPath(uploadImagePath));
			FileUtils.copyFile(upload, file);
			
			jsonMap.put(STATUS, SUCCESS);
			jsonMap.put("url", ServletActionContext.getServletContext().getContextPath() + uploadImagePath);
			
			return result(jsonMap);
		} catch (Exception e){
			jsonMap.put(STATUS, ERROR);
			e.printStackTrace();
		} finally {
			clear();
		}
		return ajaxJson(jsonMap);
	}
	
	// 媒体文件上传
	public String media() {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try{
			if (ContextUtil.getCurrentUserData() == null) {
				return ajaxJsonErrorMessage("请先登录!");
			}
			if (upload == null) {
				return ajaxJsonErrorMessage("请选择上传文件!");
			}
			String allowedUploadMediaExtension = getSystemConfig().getAllowedUploadMediaExtension().toLowerCase();
			if (StringUtils.isEmpty(allowedUploadMediaExtension)){
				return ajaxJsonErrorMessage("不允许上传媒体文件!");
			}
			String mediaExtension =  StringUtils.substringAfterLast(uploadFileName, ".").toLowerCase();
			String[] mediaExtensionArray = allowedUploadMediaExtension.split(SystemConfig.EXTENSION_SEPARATOR);
			if (!ArrayUtils.contains(mediaExtensionArray, mediaExtension)) {
				return ajaxJsonErrorMessage("只允许上传媒体文件类型: " + allowedUploadMediaExtension + "!");
			}
			int uploadLimit = getSystemConfig().getUploadLimit() * 1024;
			if (uploadLimit != 0) {
				if (upload != null && upload.length() > uploadLimit) {
					return ajaxJsonErrorMessage("文件大小超出限制!");
				}
			}
			File uploadMediaDir = new File(ServletActionContext.getServletContext().getRealPath(SystemConfig.UPLOAD_MEDIA_DIR));
			if (!uploadMediaDir.exists()) {
				uploadMediaDir.mkdirs();
			}
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMM");
			String dateString = simpleDateFormat.format(new Date());
			String uploadMediaPath = SystemConfig.UPLOAD_MEDIA_DIR + dateString + "/" + CommonUtil.getUUID() + "." + mediaExtension;
			File file = new File(ServletActionContext.getServletContext().getRealPath(uploadMediaPath));
			FileUtils.copyFile(upload, file);
			
			jsonMap.put(STATUS, SUCCESS);
			jsonMap.put("url", ServletActionContext.getServletContext().getContextPath() + uploadMediaPath);
			
			return result(jsonMap);
		} catch (Exception e){
			jsonMap.put(STATUS, ERROR);
			e.printStackTrace();
		} finally {
			clear();
		}
		return ajaxJson(jsonMap);
	}
	
	// 其它文件上传
	public String file() {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try{
			if (ContextUtil.getCurrentUserData() == null) {
				return ajaxJsonErrorMessage("请先登录!");
			}
			if (upload == null) {
				return ajaxJsonErrorMessage("请选择上传文件!");
			}
			String allowedUploadFileExtension = getSystemConfig().getAllowedUploadFileExtension().toLowerCase();
			if (StringUtils.isEmpty(allowedUploadFileExtension)){
				return ajaxJsonErrorMessage("不允许上传文件!");
			}
			String fileExtension =  StringUtils.substringAfterLast(uploadFileName, ".").toLowerCase();
			String[] fileExtensionArray = allowedUploadFileExtension.split(SystemConfig.EXTENSION_SEPARATOR);
			if (!ArrayUtils.contains(fileExtensionArray, fileExtension)) {
				return ajaxJsonErrorMessage("只允许上传文件类型: " + allowedUploadFileExtension + "!");
			}
			int uploadLimit = getSystemConfig().getUploadLimit() * 1024;
			if (uploadLimit != 0) {
				if (upload != null && upload.length() > uploadLimit) {
					return ajaxJsonErrorMessage("文件大小超出限制!");
				}
			}
			File uploadFileDir = new File(ServletActionContext.getServletContext().getRealPath(SystemConfig.UPLOAD_FILE_DIR));
			if (!uploadFileDir.exists()) {
				uploadFileDir.mkdirs();
			}
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMM");
			String dateString = simpleDateFormat.format(new Date());
			String uploadFilePath = SystemConfig.UPLOAD_FILE_DIR + dateString + "/" + CommonUtil.getUUID() + "." + fileExtension;
			File file = new File(ServletActionContext.getServletContext().getRealPath(uploadFilePath));
			FileUtils.copyFile(upload, file);
			
			jsonMap.put(STATUS, SUCCESS);
			jsonMap.put("url", ServletActionContext.getServletContext().getContextPath() + uploadFilePath);
			jsonMap.put("filename", uploadFileName);
			jsonMap.put("filetype", fileExtension);
			jsonMap.put("filesize", file.length());
			
			return result(jsonMap);
		} catch (Exception e){
			jsonMap.put(STATUS, ERROR);
			e.printStackTrace();
		} finally {
			clear();
		}
		return ajaxJson(jsonMap);
	}
	
	private String result(Map<String, Object> jsonMap){
		if("richEditor".equals(CKEditor)){
			StringBuffer sb = new StringBuffer();
			sb.append("<script type=\"text/javascript\">");
			sb.append("window.parent.CKEDITOR.tools.callFunction(");
			sb.append(CKEditorFuncNum);
			sb.append(", \"");
			sb.append(jsonMap.get("url"));
			sb.append("\",");
			sb.append(JSONObject.fromObject(jsonMap).toString());
			sb.append(")");
			sb.append("</script>");
			return ajax(sb.toString(), "text/html");
		} else {
			return ajaxJson(jsonMap);
		}
	}
	
	private void clear() {
		upload = null;
		uploadFileName = null;
		CKEditor = null;
		CKEditorFuncNum = null;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getCKEditor() {
		return CKEditor;
	}

	public void setCKEditor(String cKEditor) {
		CKEditor = cKEditor;
	}

	public String getCKEditorFuncNum() {
		return CKEditorFuncNum;
	}

	public void setCKEditorFuncNum(String cKEditorFuncNum) {
		CKEditorFuncNum = cKEditorFuncNum;
	}
}
